package io.renren.socket.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.renren.modules.iotp.entity.IOTPBean;
import io.renren.modules.iotp.entity.IOTPBody;
import io.renren.modules.iotp.utils.Code;
import io.renren.modules.iotp.utils.IotpBodyUtils;

/**
 * 向IOTS 端 发送 配置的连接
 * 
 * @author lfy.xys
 * @date 2018年5月22日
 *
 */
public class IotsConfigConnClientRunnable extends NioAbstractClient implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(IotsConfigConnClientRunnable.class);

	public IotsConfigConnClientRunnable(String ip, int port, List<byte[]> sendMsg) {
		super(ip, port, sendMsg);
	}

	@Override
	public void run() {
		try {
			logger.info(ip + ":" + port); 
			this.connect(); 
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(client!=null) {
				try {
					rBuffer.clear();
					client.close();
					logger.info("关闭 {}:{} 的连接", ip, port);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	} 
	
	int index = 0;
	@Override
	public void sendMsg() {
		logger.info(sendMsg.size()+"");
		for (byte[] msg : sendMsg) {
			logger.info(msg.length + "");
			int p = 0;
			while(p < msg.length){
				int sendSize = 0;
				try {
					sendSize = client.write(ByteBuffer.wrap(msg,p,msg.length-p));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				p += sendSize;
				if(p != msg.length && sendSize > 0){
					System.out.println("我没有发完，只发了 "+ p +" 个");
				}else if(sendSize > 0){
					System.out.println("我发完了 "+ p +" 个");
					index += p;
					System.out.println("我累计发送了 "+ index +" 个");
				}
			}
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		
//		int i = 0;
//		for (byte[] bs : sendMsg) {
//			// 循环发送 socket发送
//			// 此业务 不会出现 超长度问题
////			System.out.println(i++ + " :" + Arrays.toString(bs));
//			System.out.println(i++ + " :" + bs.length);
//			try {
//				client.write(ByteBuffer.wrap(bs));
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
		
	}

	@Override
	public boolean receiveMsg(byte[] bytes) {
		
		
		logger.info("接收到结果：{}", Arrays.toString(bytes));
		
//		IotpBodyUtils ibu = new IotpBodyUtils();
//		IOTPBean iotpBean = ibu.toIotpBean(bytes);
//		
//		IOTPBody body = iotpBean.getBody();
//		if(body != null) {
//			//解析成功
//		}else {
//			// 不成功，返回true，继续接收消息
//			return true;
//		}
//		
//		logger.info("body:" + body.toString());
//		// 获得协议体
//		List<String> list = body.getBodyList();
//		String resultMsg = list.toString();
//		logger.info("接收到结果：{}", resultMsg);
		
		// 成功，返回false，停止接收消息，close
		return false;
	}

	
}
